package wci.frontend.pascal.parsers;

import java.util.EnumSet;

import wci.frontend.*;
import wci.frontend.pascal.*;
import wci.intermediate.*;
import wci.intermediate.icodeimpl.*;

import static wci.frontend.pascal.PascalTokenType.*;
import static wci.frontend.pascal.PascalErrorCode.*;
import static wci.intermediate.icodeimpl.ICodeNodeTypeImpl.*;
import static wci.intermediate.icodeimpl.ICodeKeyImpl.*;

/**
 * <h1>IfStatementParser</h1>
 * <p>解析Pascal IF语句</p>
 * <p>Copyright (c) 2009 by Ronald Mak</p>
 * <p>For instructional purposes only.  No warranties.</p>
 */
public class IfStatementParser extends StatementParser
{
    public IfStatementParser(PascalParserTD parent)
    {
        super(parent);
    }
    // THEN的同步集合
    private static final EnumSet<PascalTokenType> THEN_SET =
        StatementParser.STMT_START_SET.clone();
    static {
        THEN_SET.add(THEN);
        THEN_SET.addAll(StatementParser.STMT_FOLLOW_SET);
    }

    public ICodeNode parse(Token token)
        throws Exception
    {
        token = nextToken(); 
        ICodeNode ifNode = ICodeFactory.createICodeNode(ICodeNodeTypeImpl.IF);
        //IF语句的条件表达式
        ExpressionParser expressionParser = new ExpressionParser(this);
        ifNode.addChild(expressionParser.parse(token));
        // THEN处同步一下
        token = synchronize(THEN_SET);
        if (token.getType() == THEN) {
            token = nextToken();
        }
        else {
            errorHandler.flag(token, MISSING_THEN, this);
        }
        //THEN后的语句
        StatementParser statementParser = new StatementParser(this);
        ifNode.addChild(statementParser.parse(token));
        token = currentToken();
        //试探后没有ELSE语句
        if (token.getType() == ELSE) {
            token = nextToken(); 
            ifNode.addChild(statementParser.parse(token));
        }
        return ifNode;
    }
}
